<template>
  <div class="ticket-system">
    <div class="ticket-header">
      <div class="header-title">
        <h2>Ticket System</h2>
        <p class="header-desc">Manage and track operation tickets</p>
      </div>

      <div class="header-actions">
        <a-space>
          <a-input-search
            v-model:value="searchText"
            placeholder="Search ticket number, title..."
            style="width: 280px"
            @search="handleSearch"
          />
          <a-button type="primary" @click="showCreateModal">
            <PlusOutlined /> Create Ticket
          </a-button>
        </a-space>
      </div>
    </div>

    <!-- 统计卡片 -->
    <div class="stats-cards">
      <a-card v-if="statistics" :loading="statsLoading">
        <a-row :gutter="16">
          <a-col :span="6">
            <a-statistic
              title="Total Tickets"
              :value="statistics.total"
              :value-style="{ color: '#1890ff' }"
            >
              <template #prefix>
                <FileTextOutlined />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="In Progress"
              :value="statistics.byStatus.inProgress"
              :value-style="{ color: '#faad14' }"
            >
              <template #prefix>
                <SyncOutlined spin />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="Resolved"
              :value="statistics.byStatus.resolved"
              :value-style="{ color: '#52c41a' }"
            >
              <template #prefix>
                <CheckCircleOutlined />
              </template>
            </a-statistic>
          </a-col>
          <a-col :span="6">
            <a-statistic
              title="SLA Breached"
              :value="statistics.slaBreached"
              :value-style="{ color: '#ff4d4f' }"
            >
              <template #prefix>
                <ClockCircleOutlined />
              </template>
            </a-statistic>
          </a-col>
        </a-row>
      </a-card>
    </div>

    <!-- 筛选器 -->
    <div class="ticket-filters">
      <a-space wrap>
        <span class="filter-label">Status:</span>
        <a-checkbox-group v-model:value="filters.status" @change="handleFilterChange">
          <a-checkbox value="open">Open</a-checkbox>
          <a-checkbox value="in_progress">In Progress</a-checkbox>
          <a-checkbox value="pending">Pending</a-checkbox>
          <a-checkbox value="resolved">Resolved</a-checkbox>
          <a-checkbox value="closed">Closed</a-checkbox>
        </a-checkbox-group>

        <a-divider type="vertical" />

        <span class="filter-label">Priority:</span>
        <a-checkbox-group v-model:value="filters.priority" @change="handleFilterChange">
          <a-checkbox value="critical">
            <a-tag color="red" size="small">Critical</a-tag>
          </a-checkbox>
          <a-checkbox value="high">
            <a-tag color="orange" size="small">High</a-tag>
          </a-checkbox>
          <a-checkbox value="medium">
            <a-tag color="blue" size="small">Medium</a-tag>
          </a-checkbox>
          <a-checkbox value="low">
            <a-tag size="small">Low</a-tag>
          </a-checkbox>
        </a-checkbox-group>

        <a-divider type="vertical" />

        <span class="filter-label">Type:</span>
        <a-checkbox-group v-model:value="filters.type" @change="handleFilterChange">
          <a-checkbox value="incident">Incident</a-checkbox>
          <a-checkbox value="alert">Alert</a-checkbox>
          <a-checkbox value="maintenance">Maintenance</a-checkbox>
          <a-checkbox value="request">Request</a-checkbox>
        </a-checkbox-group>

        <a-button size="small" @click="resetFilters">Reset</a-button>
      </a-space>
    </div>

    <!-- 视图切换 -->
    <div class="view-toggle">
      <a-radio-group v-model:value="viewMode" button-style="solid">
        <a-radio-button value="board">
          <AppstoreOutlined /> Board View
        </a-radio-button>
        <a-radio-button value="list">
          <UnorderedListOutlined /> List View
        </a-radio-button>
      </a-radio-group>
    </div>

    <!-- 主内容区 -->
    <div class="ticket-content">
      <!-- 看板视图 -->
      <TicketBoard v-if="viewMode === 'board'" />

      <!-- 列表视图 -->
      <div v-else class="ticket-list">
        <a-table
          :columns="columns"
          :data-source="ticketStore.tickets"
          :loading="ticketStore.loading"
          :pagination="{
            current: filters.page,
            pageSize: filters.pageSize,
            total: ticketStore.total,
            showSizeChanger: true,
            showTotal: (total: number) => `Total ${total} items`,
          }"
          row-key="_id"
          @change="handleTableChange"
        >
          <template #bodyCell="{ column, record }">
            <template v-if="column.key === 'ticketNumber'">
              <router-link :to="`/tickets/${record._id}`">
                {{ record.ticketNumber }}
              </router-link>
            </template>

            <template v-else-if="column.key === 'title'">
              <div class="ticket-title-cell">
                {{ record.title }}
                <div class="ticket-tags">
                  <a-tag v-for="tag in record.tags?.slice(0, 2)" :key="tag" size="small">
                    {{ tag }}
                  </a-tag>
                </div>
              </div>
            </template>

            <template v-else-if="column.key === 'priority'">
              <a-tag :color="getPriorityColor(record.priority)">
                {{ getPriorityLabel(record.priority) }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'status'">
              <a-tag :color="getStatusColor(record.status)">
                {{ getStatusLabel(record.status) }}
              </a-tag>
            </template>

            <template v-else-if="column.key === 'type'">
              <component :is="getTypeIcon(record.type)" />
              {{ getTypeLabel(record.type) }}
            </template>

            <template v-else-if="column.key === 'assignedTo'">
              <template v-if="record.assignedTo">
                <a-avatar size="small">
                  {{ record.assignedTo.username.charAt(0).toUpperCase() }}
                </a-avatar>
                <span style="margin-left: 8px">{{ record.assignedTo.username }}</span>
              </template>
              <span v-else style="color: #999">Unassigned</span>
            </template>

            <template v-else-if="column.key === 'createdAt'">
              {{ dayjs(record.createdAt).fromNow() }}
            </template>

            <template v-else-if="column.key === 'actions'">
              <a-space>
                <a-button type="link" size="small" @click="router.push(`/tickets/${record._id}`)">
                  View
                </a-button>
              </a-space>
            </template>
          </template>
        </a-table>
      </div>
    </div>

    <!-- 创建工单弹窗 -->
    <CreateTicketModal
      v-model="createModalVisible"
      :users="users"
      @success="handleCreateSuccess"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, reactive, onMounted } from 'vue'
import { useRouter } from 'vue-router'
import dayjs from 'dayjs'
import {
  PlusOutlined,
  AppstoreOutlined,
  UnorderedListOutlined,
  FileTextOutlined,
  SyncOutlined,
  CheckCircleOutlined,
  ClockCircleOutlined,
  BugOutlined,
  BellOutlined,
  ToolOutlined,
  FileAddOutlined,
} from '@ant-design/icons-vue'
import { useTicketStore } from '@/stores/ticketStore'
import TicketBoard from '@/components/tickets/TicketBoard.vue'
import CreateTicketModal from '@/components/tickets/CreateTicketModal.vue'
import type { TableColumnsType } from 'ant-design-vue'
import type { Ticket } from '@/api/ticket'

const router = useRouter()
const ticketStore = useTicketStore()

const viewMode = ref<'board' | 'list'>('board')
const searchText = ref('')
const createModalVisible = ref(false)
const statsLoading = ref(false)
const statistics = ref<any>(null)
const users = ref<any[]>([])

const filters = reactive({
  status: [] as string[],
  priority: [] as string[],
  type: [] as string[],
  search: '',
  page: 1,
  pageSize: 20,
})

const columns: TableColumnsType<Ticket> = [
  { title: 'Ticket Number', dataIndex: 'ticketNumber', key: 'ticketNumber', width: 160 },
  { title: 'Title', dataIndex: 'title', key: 'title', ellipsis: true },
  { title: 'Type', dataIndex: 'type', key: 'type', width: 100 },
  { title: 'Priority', dataIndex: 'priority', key: 'priority', width: 100 },
  { title: 'Status', dataIndex: 'status', key: 'status', width: 100 },
  { title: 'Assignee', dataIndex: 'assignedTo', key: 'assignedTo', width: 150 },
  { title: 'Created At', dataIndex: 'createdAt', key: 'createdAt', width: 120 },
  { title: 'Actions', key: 'actions', width: 100, fixed: 'right' },
]

const getPriorityColor = (priority: string) => {
  const colors: Record<string, string> = {
    critical: 'red',
    high: 'orange',
    medium: 'blue',
    low: 'default',
  }
  return colors[priority] || 'default'
}

const getPriorityLabel = (priority: string) => {
  const labels: Record<string, string> = {
    critical: 'Critical',
    high: 'High',
    medium: 'Medium',
    low: 'Low',
  }
  return labels[priority] || priority
}

const getStatusColor = (status: string) => {
  const colors: Record<string, string> = {
    open: 'blue',
    in_progress: 'orange',
    pending: 'gold',
    resolved: 'green',
    closed: 'default',
  }
  return colors[status] || 'default'
}

const getStatusLabel = (status: string) => {
  const labels: Record<string, string> = {
    open: 'Open',
    in_progress: 'In Progress',
    pending: 'Pending',
    resolved: 'Resolved',
    closed: 'Closed',
  }
  return labels[status] || status
}

const getTypeIcon = (type: string) => {
  const icons: Record<string, any> = {
    incident: BugOutlined,
    alert: BellOutlined,
    maintenance: ToolOutlined,
    request: FileAddOutlined,
  }
  return icons[type] || BugOutlined
}

const getTypeLabel = (type: string) => {
  const labels: Record<string, string> = {
    incident: 'Incident',
    alert: 'Alert',
    maintenance: 'Maintenance',
    request: 'Request',
  }
  return labels[type] || type
}

const handleSearch = () => {
  filters.search = searchText.value
  handleFilterChange()
}

const handleFilterChange = () => {
  ticketStore.fetchTickets(filters)
}

const resetFilters = () => {
  filters.status = []
  filters.priority = []
  filters.type = []
  filters.search = ''
  searchText.value = ''
  handleFilterChange()
}

const handleTableChange = (pagination: any) => {
  filters.page = pagination.current
  filters.pageSize = pagination.pageSize
  handleFilterChange()
}

const showCreateModal = () => {
  createModalVisible.value = true
}

const handleCreateSuccess = () => {
  ticketStore.fetchTickets(filters)
  fetchStatistics()
}

const fetchStatistics = async () => {
  statsLoading.value = true
  try {
    statistics.value = await ticketStore.fetchStatistics()
  } finally {
    statsLoading.value = false
  }
}

onMounted(() => {
  // Only fetch if we don't have tickets data yet
  if (ticketStore.tickets.length === 0) {
    ticketStore.fetchTickets(filters)
    fetchStatistics()
  }
  // TODO: 从 API 获取用户列表
  users.value = []
})
</script>

<style scoped lang="scss">
.ticket-system {
  height: 100%;
  display: flex;
  flex-direction: column;
  background: #f5f5f5;
}

.ticket-header {
  background: white;
  padding: 20px 24px;
  border-bottom: 1px solid #f0f0f0;
  display: flex;
  justify-content: space-between;
  align-items: center;

  .header-title {
    h2 {
      margin: 0;
      font-size: 24px;
    }

    .header-desc {
      margin: 4px 0 0;
      color: #666;
      font-size: 14px;
    }
  }
}

.stats-cards {
  padding: 16px 24px;
  background: white;
  border-bottom: 1px solid #f0f0f0;
}

.ticket-filters {
  background: white;
  padding: 16px 24px;
  border-bottom: 1px solid #f0f0f0;

  .filter-label {
    font-weight: 500;
    color: #666;
  }
}

.view-toggle {
  background: white;
  padding: 12px 24px;
  border-bottom: 1px solid #f0f0f0;
}

.ticket-content {
  flex: 1;
  overflow: hidden;
  background: white;
}

.ticket-list {
  padding: 16px 24px;
  height: 100%;
  overflow: auto;
}

.ticket-title-cell {
  .ticket-tags {
    margin-top: 4px;
  }
}
</style>
